#encoding=utf-8
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression, SGDRegressor, Ridge
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error

def mylinear():

    #获取数据
    lb = load_boston()
    # print('原数据：',lb.data)

    #分割数据到训练集和测试集
    x_train, x_test, y_train, y_test =  train_test_split(lb.data, lb.target, test_size=0.25)
    print('真实值：', y_test)

    #进行标准化处理:目的 所有的数据变的非常小
    std_x = StandardScaler()

    x_train = std_x.fit_transform(x_train)
    x_test = std_x.transform(x_test)

    #目标值
    std_y = StandardScaler()

    y_train = std_y.fit_transform(y_train.reshape(-1, 1)) #.reshape(-1,1)
    y_test = std_y.transform(y_test.reshape(-1, 1))

    #estimator预测  正规方程求解方式预测结果
    lr = LinearRegression()
    lr.fit(x_train, y_train) #y_train:目标值

    print(lr.coef_)

    #预测测试集的房子价格
    y_predict = std_y.inverse_transform(lr.predict(x_test))

    # print("正规方程预测集里每个房子的预测价格：", y_predict)
    print("正规方程的均方误差:", mean_squared_error(std_y.inverse_transform(y_test), y_predict))

    # 梯度下降
    sgd = SGDRegressor()
    sgd.fit(x_train, y_train)  # y_train:目标值

    print(sgd.coef_)
    y_sgd_predict = std_y.inverse_transform(sgd.predict(x_test))
    # print("用梯度下降法预测房价:", y_sgd_predict)
    print("用梯度下降法的均方误差:", mean_squared_error(std_y.inverse_transform(y_test), y_sgd_predict))

    # 岭回归
    rd = Ridge(alpha=1.0)
    rd.fit(x_train, y_train)  # y_train:目标值

    print(rd.coef_)
    y_rd_predict = std_y.inverse_transform(rd.predict(x_test))
    print("用岭回归法的均方误差:", mean_squared_error(std_y.inverse_transform(y_test), y_rd_predict))

    return None


if __name__ == "__main__":
    mylinear()